package com.lky.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lky.common.constant.ProductConstant;
import com.lky.mall.product.dao.AttrAttrgroupRelationDao;
import com.lky.mall.product.dao.AttrGroupDao;
import com.lky.mall.product.dao.CategoryDao;
import com.lky.mall.product.entity.AttrAttrgroupRelationEntity;
import com.lky.mall.product.entity.AttrGroupEntity;
import com.lky.mall.product.entity.CategoryEntity;
import com.lky.mall.product.service.CategoryService;
import com.lky.mall.product.vo.AttrRespVo;
import com.lky.mall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lky.common.utils.PageUtils;
import com.lky.common.utils.Query;

import com.lky.mall.product.dao.AttrDao;
import com.lky.mall.product.entity.AttrEntity;
import com.lky.mall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAattr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //保存基本信息
        this.save(attrEntity);
        //保存关联关系
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attr.getAttrId());
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        attrAttrgroupRelationDao.insert(relationEntity);
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        //如果有key字段 需要模糊查询
        LambdaQueryWrapper<AttrEntity> queryWrapper = Wrappers.lambdaQuery();

        if (StringUtils.isNotBlank((String)params.get("key"))) {
            String key = (String)params.get("key");
            queryWrapper.and(wrapper ->
                    wrapper.eq(AttrEntity::getAttrId, key)
                            .or()
                            .like(AttrEntity::getAttrName, "%" + key + "%")
            );
        }
        //catelogId == 0 查询全部
        if (catelogId == 0) {
            //select * from pms_attr where attr_type = ? or (atty_id = key or attr_name like %key%)
            queryWrapper.eq(AttrEntity::getAttrType,"base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPE_BASE:ProductConstant.AttrEnum.ATTR_TYPE_SALE);
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryWrapper
            );
            //在上面查出的数据基础上还需要返回catelogName和groupName
            PageUtils pageUtils = new PageUtils(page);
            List<AttrEntity> records = page.getRecords();
            List<AttrRespVo> respVos = records.stream().map(attrEntity -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(attrEntity, attrRespVo);
                //获取catelogName和groupName
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectById(attrEntity.getAttrId());
                if (attrAttrgroupRelationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if (categoryEntity != null) {
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }
                return attrRespVo;
            }).collect(Collectors.toList());

            pageUtils.setList(respVos);
            return pageUtils;
        } else {
            //select * from pms_attr where catelog_id = ? and attr_type = ? or (atty_id = key or attr_name like %key%)
            queryWrapper.eq(AttrEntity::getCatelogId, catelogId).eq(AttrEntity::getAttrType,"base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE:ProductConstant.AttrEnum.ATTR_TYPE_SALE);
            IPage<AttrEntity> page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryWrapper
            );
            //在上面查出的数据基础上还需要返回catelogName和groupName
            PageUtils pageUtils = new PageUtils(page);
            List<AttrEntity> records = page.getRecords();
            List<AttrRespVo> respVos = records.stream().map(attrEntity -> {
                AttrRespVo attrRespVo = new AttrRespVo();
                BeanUtils.copyProperties(attrEntity, attrRespVo);
                //获取catelogName和groupName
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectById(attrEntity.getAttrId());
                if (attrAttrgroupRelationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                if (categoryEntity != null) {
                    attrRespVo.setCatelogName(categoryEntity.getName());
                }
                return attrRespVo;
            }).collect(Collectors.toList());

            pageUtils.setList(respVos);
            return pageUtils;
        }
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,respVo);

        //1.分组信息（pms_attr 和 pms_attr_group 和 关联表pms_attr_attrgroup_relation）
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (relationEntity != null){
            respVo.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if (attrGroupEntity != null){
                respVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }

        //2.设置分类信息(pms_brand 和 pms_category 和关联表 pms_category_brand_relation)
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null){
            respVo.setCatelogName(categoryEntity.getName());
        }

        return respVo;
    }


    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        //修改分组关联
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        relationEntity.setAttrId(attr.getAttrId());

        Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        //没有记录则做新增操作
        if (count > 0){
            attrAttrgroupRelationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
        }else {
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    /*
    * 用attrgroupId从pms_attr_attrgroup_relation表中获得attr_id,再根据attr_id查pms_attr表
    * */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        List<AttrEntity> attrEntities = this.listByIds(attrIds);
        return attrEntities;
    }

    /*
     * 获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
     * */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、根据自身id（attrgroupId）在attrGroup表查找分类id（catelogId）
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1、根据分类id（catelogId）在attrGroup表查找数据，并获得数据中的attrgroupId
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));

        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2.2、通关分类id（catelogId）在关联表查找属性id(attrid)，通过stream流获得所有属性id(attrid)，查到的属性id就是已经绑定的数据
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", collect));

        List<Long> collect1 = relationEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //2.3、在属性表Attr中通过分类id（catelogId）查找出所有的基本属性数据，notIn可以排除已经绑定的数据
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                //只查基本属性
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (collect1 != null && collect1.size() > 0){
            queryWrapper.notIn("attr_id", collect1);
        }
        //模糊查询
        if (StringUtils.isNotBlank((String)params.get("key"))){
            String key = (String) params.get("key");
            queryWrapper.and(w ->
                w.eq("attr_id",key)
                        .or()
                        .like("attr_name",key)
            );
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void deleteRelation(List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntity) {
        attrAttrgroupRelationDao.deleteBatchRelation(attrAttrgroupRelationEntity);
    }
}